import React from 'react';
import { Modal, Spin, Card, Button, Switch, Select, Input, Tooltip, Icon, Tabs, notification } from 'antd';
import * as actions from './../../../actions/backstage/carouselAction';
import TableView from './../TableView';
const { Option } = Select;
const TextArea = Input.TextArea;
const TabPane = Tabs.TabPane;

export default class carouselManage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            updateCarouselLoading: false,
            addCarouselImg: false,
            serverData: [],
            requestData: {},
            productData: null,
            searchObject: {},
            articleFlap: 'add',
            btnSaveDisabled: true,
            productType: "1",
            carouselWidth: 535,
            carouselHeight: 212
        }
    }
    componentDidMount(){
        this.onRefreshData();
    }
    onRefreshData(){
        actions.findCarousels(this, { whichType: true });
    }
    selectType(val){
        this.setState({productType: val});
    }
    addCarouselImg(){
        this.state.fileVerify = false;
        this.setState({addCarouselImg: true, articleFlap: 'add', requestData: {}, btnSaveDisabled: false});
    }
    btnShowCarousel(val){
        this.setState({addCarouselImg: val});
        if(val == false){
            $("#carouselPic").val('');
            document.getElementById("imgPreview").src = "/src/styles/images/defaultType.png";
            this.setState({
              productType: "1",
              productData: null
            });
        }
    }
    //尺寸：1920 x 350（px）
    getImgSize(imgFile){
        var that = this;
        var reader = new FileReader();
        reader.readAsDataURL(imgFile.files[0])
        reader.onload = function (e) {
           var image = new Image();
           image.src = e.target.result;
           image.onload= () => {
             if(image.naturalWidth != that.state.carouselWidth || image.naturalHeight != that.state.carouselHeight){
                 notification.warn({
                     placement: 'bottomRight',
                     message: '提示：',
                     description: '图片尺寸: 必须是 ' + that.state.carouselWidth + ' * ' + that.state.carouselHeight + ' 像素。',
                     style: {
                       borderLeft: '4px solid rgb(255, 191, 0)'
                     }
                 });
                 that.state.fileVerify = false;
                 document.getElementById("imgPreview").src = "/src/styles/images/defaultType.png";
             }else{
                 that.state.fileVerify = true;
                 document.getElementById("imgPreview").src = e.target.result;
             }
   	      }
       }
    }
    verifyMsgAndImage(){
        if($("#carouselPic")[0].files.length >= 1){
            var file = $("#carouselPic")[0].files[0];
            if (!(file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/bmp')) {
              notification.warn({
                  placement: 'bottomRight',
                  message: '提示：',
                  description: '你只能选择 JPG, PNG, GIF 和 BMP。',
                  style: {
                    borderLeft: '4px solid rgb(255, 191, 0)'
                  }
              });
              this.state.fileVerify = false;
              document.getElementById("imgPreview").src = "/src/styles/images/defaultType.png";
              return;
            }
            const isLt2M = file.size < 819200; // 大小：800k
            if (!isLt2M) {
              notification.warn({
                  placement: 'bottomRight',
                  message: '提示：',
                  description: '图片大小小于 800 KB。',
                  style: {
                    borderLeft: '4px solid rgb(255, 191, 0)'
                  }
              });
              this.state.fileVerify = false;
              document.getElementById("imgPreview").src = "/src/styles/images/defaultType.png";
              return;
            }
            this.getImgSize($("#carouselPic")[0]);
        }
    }
    btnSaveCarouselImg(){
        if(this.state.articleFlap == 'add'){
            if($("#carouselPic")[0].files.length >= 1){
                if(this.state.fileVerify == true){
                    if(this.state.isHaveProduct == true && this.state.productData != null){
                      this.state.requestData.pId = this.state.productData.id;
                    }else {
                      delete this.state.requestData.productId;
                    }
                    this.state.requestData.whichType = true;
                    this.state.requestData.type = this.state.productType;
                    actions.addOrEditCarousel(this, this.state.requestData, "add");
                }else{
                    notification.warn({
                        placement: 'bottomRight',
                        message: '提示',
                        description: '文件类型, 尺寸大小(' + this.state.carouselWidth + ' * ' + this.state.carouselHeight + ') 错误。',
                        style: {
                          borderLeft: '4px solid rgb(255, 191, 0)'
                        }
                    });
                }
            }else{
                notification.warn({
                    placement: 'bottomRight',
                    message: '提示：',
                    description: '类型图 必须选择。',
                    style: {
                      borderLeft: '4px solid rgb(255, 191, 0)'
                    }
                });
            }
        }else {
            if($("#carouselPic")[0].files.length >= 1){
                if(this.state.fileVerify == true){
                    if(this.state.isHaveProduct == true && this.state.productData != null){
                      this.state.requestData.pId = this.state.productData.id;
                    }else {
                      delete this.state.requestData.productId;
                    }
                    actions.addOrEditCarousel(this, this.state.requestData, "edite");
                }else{
                    notification.warn({
                        placement: 'bottomRight',
                        message: '提示：',
                        description: '文件类型, 尺寸大小(' + this.state.carouselWidth + ' * ' + this.state.carouselHeight + ') 错误。',
                        style: {
                          borderLeft: '4px solid rgb(255, 191, 0)'
                        }
                    });
                }
            }else{
                if(this.state.isHaveProduct == true && this.state.productData != null){
                  this.state.requestData.pId = this.state.productData.id;
                }else {
                  delete this.state.requestData.productId;
                }
                actions.addOrEditCarousel(this, this.state.requestData, "edite");
            }
        }
    }
    onChangeDescribe(val){
        this.setState({
          requestData: {
              ...this.state.requestData,
              describe: val.target.value
          }
        });
    }
    onImgLoad(e){
        $(e.currentTarget).css("backgroundImage", "none");
    }
    editCarousel(item){
        var that = this;
        this.setState({requestData: item, articleFlap:'edite', addCarouselImg: true, btnSaveDisabled: true, productType: item.type});
        setTimeout(function(){
            document.getElementById("imgPreview").src = "http://tinsley.oss-cn-shenzhen.aliyuncs.com/" + item.pic;
            if(item.productId != undefined){
                actions.findProductDetial(that, item.productId);
            }else{
                that.setState({btnSaveDisabled: false});
            }
        }, 1000);
    }
    renderImageItem(item, index){
        return <div key={index} className="divCarouselItem" style={{width: '618px', marginRight: '0px'}}>
            <img style={{ width: '618px', height: 'initial'}} src={"http://tinsley.oss-cn-shenzhen.aliyuncs.com/" + item.pic} onClick={this.editCarousel.bind(this, item)} onLoad={this.onImgLoad.bind(this)}/>
            <div className="divDescribe divDescribeType" style={{width: '618px'}} title={item.describe} onClick={this.editCarousel.bind(this, item)}>
              {"创建时间: " + new Date(item.createTime).Format("yyyy-MM-dd hh:mm") + ((item.updateTime == undefined)?"": ", 修改时间: " + new Date(item.updateTime).Format("yyyy-MM-dd hh:mm"))}<br />
              {"描述: " + ((item.describe == undefined)?"无":item.describe)}
            </div>
        </div>
    }
    render() {
      var serverList = null;
      if(this.state.serverData.length != 0){
          serverList = <div style={{marginTop: '10px', display: 'flex', flexWrap: 'wrap', justifyContent: 'space-around'}} >
            {
                this.state.serverData.map((item, index) => {
                    return this.renderImageItem(item, index);
                })
            }
          </div>
      }else{
          serverList = <div className="divEmptyData">对不起，没有可用数据。</div>
      }
      var btnAddCarouselImg = null;
      if(this.state.serverData.length <= 5){
          btnAddCarouselImg = <Button icon="plus-circle-o" type="primary" onClick={this.addCarouselImg.bind(this)}>添加类型图</Button>
      }else{
          btnAddCarouselImg = <span style={{color: '#ec1e1e', fontSize: '14px'}}>类型图最多 6 张，尺寸：{this.state.carouselWidth} * {this.state.carouselHeight}（像素）。</span>
      }
      return (
          <div>
              <div className="divUpdateVideo">
                  {btnAddCarouselImg}
              </div>
              {serverList}
              <Modal
                  title="添加 类型图"
                  visible={this.state.addCarouselImg}
                  wrapClassName="vertical-center-modal"
                  footer={null}
                  onCancel={this.btnShowCarousel.bind(this, false)}
                  width="auto"
                  maskClosable={false}
              >
                  <Spin spinning={this.state.updateCarouselLoading} tip="上传中，请稍候...">
                      <Tabs defaultActiveKey="1">
                        <TabPane tab="选择类型图" key="1">
                            <div style={{height: '95px', marginBottom: '5px'}}>
                                <div style={{marginTop: '36px', marginLeft: '4px', display: 'inline-block',}}>
                                    <Tooltip placement="bottomRight" title="请选择类型图">
                                        <input id="carouselPic" type="file" className="inputFile" onChange={this.verifyMsgAndImage.bind(this)} />
                                        <Button icon="picture" type="primary" className="btnClose btnGreen">选择类型图</Button>
                                    </Tooltip>
                                </div>
                                <img id="imgPreview" style={{verticalAlign: 'middle', width: '262px', marginLeft: '201px', position: 'absolute', marginTop: '-4px'}} src="/src/styles/images/defaultType.png" title={"尺寸 (像素): " + this.state.carouselWidth + " * " + this.state.carouselHeight} />
                            </div>
                        </TabPane>
                      </Tabs>

                      <Tabs defaultActiveKey="1">
                        <TabPane tab="选择类型" key="1">
                            <div style={{marginLeft: '7px'}}>
                              类型：&nbsp;&nbsp;<Select value={this.state.productType} disabled={true} style={{ width: 120 }} onChange={this.selectType.bind(this)}>
                                <Option value="1">推荐品牌</Option>
                                <Option value="2">女孩护肤</Option>
                                <Option value="3">面膜</Option>
                                <Option value="4">彩妆/口红</Option>
                                <Option value="5">个人护理</Option>
                                <Option value="6">保健产品</Option>
                              </Select>
                            </div>
                        </TabPane>
                      </Tabs>
                      <Tabs defaultActiveKey="1">
                        <TabPane tab="描述信息" key="1">
                            <div className="divItem">
                                <Tooltip placement="bottomLeft" title="请输入描述 (必填)">
                                    <TextArea placeholder="请输入描述..." value={this.state.requestData.describe} style={{width: '600px',height: '90px', margin: '2px', resize: 'none'}} className="iptAuthor" type="textarea" rows={4} onChange={(val)=>this.onChangeDescribe(val)}/>
                                </Tooltip>
                            </div>
                        </TabPane>
                      </Tabs>

                      <div style={{textAlign: 'right', marginTop: '10px'}}>
                          <Button icon="close" style={{marginRight: '15px'}} onClick={this.btnShowCarousel.bind(this, false)}>取 消</Button>
                          <Tooltip placement="bottomRight" title="保存类型图">
                              <Button icon="save" type="primary" className="btnClose" onClick={this.btnSaveCarouselImg.bind(this)} disabled={this.state.btnSaveDisabled}>保 存</Button>
                          </Tooltip>
                      </div>
                  </Spin>
              </Modal>
          </div>
      )
    }
}
